<template>
  <view class="my-posts-page">
    <!-- 自定义导航栏 -->
    <nav-bar title="我的帖子" :show-back="true"></nav-bar>
    
    <!-- 帖子类型切换 -->
    <view class="tab-switch">
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        全部
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'published' }"
        @click="switchTab('published')"
      >
        已发布
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'pending' }"
        @click="switchTab('pending')"
      >
        审核中
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'hidden' }"
        @click="switchTab('hidden')"
      >
        已隐藏
      </view>
    </view>
    
    <!-- 帖子列表 -->
    <scroll-view 
      class="post-list"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="filteredPosts.length > 0">
        <view 
          v-for="post in filteredPosts" 
          :key="post.id"
          class="post-item"
          @click="viewPostDetail(post)"
        >
          <view class="post-header">
            <text class="post-status" :class="post.status">{{ getStatusText(post.status) }}</text>
            <text class="post-date">{{ formatDate(post.createTime) }}</text>
          </view>
          
          <view class="post-content">
            <view class="post-info">
              <text class="post-title">{{ post.title || '无标题' }}</text>
              <text class="post-summary">{{ post.content }}</text>
            </view>
            <view class="post-image" v-if="post.images && post.images.length > 0">
              <image :src="post.images[0]" mode="aspectFill"></image>
            </view>
          </view>
          
          <view class="post-footer">
            <view class="post-stats">
              <view class="stat-item">
                <tn-icon name="eye" size="24" color="#999999"></tn-icon>
                <text>{{ post.viewCount }}</text>
              </view>
              <view class="stat-item">
                <tn-icon name="like" size="24" color="#999999"></tn-icon>
                <text>{{ post.likeCount }}</text>
              </view>
              <view class="stat-item">
                <tn-icon name="comment" size="24" color="#999999"></tn-icon>
                <text>{{ post.commentCount }}</text>
              </view>
            </view>
            
            <view class="post-actions">
              <view 
                class="action-pin" 
                v-if="post.status === 'published'"
                @click.stop="pinPost(post)"
              >
                <tn-icon name="top" size="24" color="#FF9800"></tn-icon>
                <text>置顶</text>
              </view>
              <view 
                class="action-edit" 
                @click.stop="editPost(post)"
                v-if="['published', 'hidden'].includes(post.status)"
              >
                <tn-icon name="edit" size="24" color="#32C5FF"></tn-icon>
                <text>编辑</text>
              </view>
              <view 
                class="action-delete" 
                @click.stop="confirmDelete(post)"
              >
                <tn-icon name="delete" size="24" color="#FF5252"></tn-icon>
                <text>删除</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 无数据状态 -->
      <view v-else class="empty-state">
        <image src="/static/images/empty-post.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无帖子数据</text>
        <button class="create-btn" @click="createPost">发布帖子</button>
      </view>
      
      <!-- 加载更多 -->
      <view class="loading-more" v-if="hasMore && filteredPosts.length > 0">
        <tn-loading mode="circle" size="24"></tn-loading>
        <text>加载更多...</text>
      </view>
      
      <view class="no-more" v-if="!hasMore && filteredPosts.length > 0">
        <text>没有更多帖子了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import NavBar from '@/components/navbar/NavBar.vue';

// 当前选中的标签
const activeTab = ref('all');

// 帖子列表
const posts = ref([]);
const isRefreshing = ref(false);
const hasMore = ref(true);

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
};

// 过滤帖子
const filteredPosts = computed(() => {
  if (activeTab.value === 'all') {
    return posts.value;
  }
  return posts.value.filter(post => post.status === activeTab.value);
});

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'published': '已发布',
    'pending': '审核中',
    'hidden': '已隐藏'
  };
  return statusMap[status] || status;
};

// 日期格式化
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const now = new Date();
  
  // 今天的日期
  if (date.toDateString() === now.toDateString()) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `今天 ${hours}:${minutes}`;
  }
  
  // 昨天的日期
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天';
  }
  
  // 一周内的日期
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const dayDiff = Math.floor((now - date) / (24 * 60 * 60 * 1000));
  if (dayDiff < 7) {
    return weekDays[date.getDay()];
  }
  
  // 更早的日期
  return `${date.getMonth() + 1}-${date.getDate()}`;
};

// 查看帖子详情
const viewPostDetail = (post) => {
  uni.navigateTo({
    url: `/pages/detail/post-detail?id=${post.id}`
  });
};

// 置顶帖子
const pinPost = (post) => {
  uni.navigateTo({
    url: `/pages/publish/pin?id=${post.id}&type=post`
  });
};

// 编辑帖子
const editPost = (post) => {
  uni.navigateTo({
    url: `/pages/publish/post?id=${post.id}&edit=true`
  });
};

// 发布新帖子
const createPost = () => {
  uni.navigateTo({
    url: '/pages/publish/post'
  });
};

// 确认删除
const confirmDelete = (post) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条帖子吗？删除后无法恢复',
    confirmColor: '#FF5252',
    success: (res) => {
      if (res.confirm) {
        deletePost(post);
      }
    }
  });
};

// 删除帖子
const deletePost = (post) => {
  // 实际项目中应该调用API删除帖子
  const index = posts.value.findIndex(item => item.id === post.id);
  if (index !== -1) {
    posts.value.splice(index, 1);
    
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    });
  }
};

// 加载更多
const loadMore = () => {
  if (!hasMore.value) return;
  
  console.log('加载更多帖子');
  
  // 实际项目中应该调用API加载更多帖子
  // 模拟加载
  setTimeout(() => {
    if (posts.value.length >= 20) {
      hasMore.value = false;
      return;
    }
    
    // 模拟新数据
    const newPosts = generateMockPosts(posts.value.length + 1, 5);
    posts.value = [...posts.value, ...newPosts];
  }, 1000);
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  
  // 实际项目中应该调用API刷新帖子列表
  console.log('刷新帖子列表');
  
  // 模拟刷新完成
  setTimeout(() => {
    isRefreshing.value = false;
    
    // 重置数据
    initPosts();
  }, 1000);
};

// 生成模拟帖子数据
const generateMockPosts = (startId, count) => {
  const result = [];
  const statuses = ['published', 'pending', 'hidden'];
  
  for (let i = 0; i < count; i++) {
    const id = startId + i;
    const hasImage = Math.random() > 0.3;
    const imageCount = hasImage ? Math.floor(Math.random() * 3) + 1 : 0;
    const images = [];
    
    for (let j = 0; j < imageCount; j++) {
      const imgId = Math.floor(Math.random() * 100);
      images.push(`https://picsum.photos/id/${imgId}/200/200`);
    }
    
    result.push({
      id,
      title: id % 3 === 0 ? '' : `测试帖子标题 ${id}`,
      content: `这是一条测试帖子的内容，用于展示帖子列表的样式和布局。这是帖子${id}的内容。`,
      images,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      createTime: new Date(new Date().getTime() - id * 3600000 * 24),
      viewCount: Math.floor(Math.random() * 100),
      likeCount: Math.floor(Math.random() * 50),
      commentCount: Math.floor(Math.random() * 20)
    });
  }
  
  return result;
};

// 初始化帖子列表
const initPosts = () => {
  posts.value = generateMockPosts(1, 10);
  hasMore.value = true;
};

onMounted(() => {
  // 初始化帖子列表
  initPosts();
});
</script>

<style lang="scss" scoped>
.my-posts-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.tab-switch {
  display: flex;
  background-color: #ffffff;
  padding: 20rpx 0;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  
  .tab-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60rpx;
    font-size: 28rpx;
    color: #666666;
    position: relative;
    
    &.active {
      color: #32C5FF;
      font-weight: bold;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -10rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background-color: #32C5FF;
        border-radius: 4rpx;
      }
    }
  }
}

.post-list {
  flex: 1;
  padding: 20rpx;
}

.post-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.post-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
  
  .post-status {
    font-size: 24rpx;
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
    
    &.published {
      background-color: rgba(76, 175, 80, 0.1);
      color: #4CAF50;
    }
    
    &.pending {
      background-color: rgba(255, 152, 0, 0.1);
      color: #FF9800;
    }
    
    &.hidden {
      background-color: rgba(158, 158, 158, 0.1);
      color: #9E9E9E;
    }
  }
  
  .post-date {
    font-size: 24rpx;
    color: #999999;
  }
}

.post-content {
  display: flex;
  margin-bottom: 16rpx;
  
  .post-info {
    flex: 1;
    padding-right: 16rpx;
    
    .post-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333333;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      overflow: hidden;
      margin-bottom: 8rpx;
    }
    
    .post-summary {
      font-size: 26rpx;
      color: #666666;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }
  
  .post-image {
    width: 150rpx;
    height: 150rpx;
    border-radius: 8rpx;
    overflow: hidden;
    flex-shrink: 0;
    
    image {
      width: 100%;
      height: 100%;
    }
  }
}

.post-footer {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #f5f5f5;
  padding-top: 16rpx;
  
  .post-stats {
    display: flex;
    
    .stat-item {
      display: flex;
      align-items: center;
      margin-right: 20rpx;
      
      text {
        font-size: 24rpx;
        color: #999999;
        margin-left: 6rpx;
      }
    }
  }
  
  .post-actions {
    display: flex;
    
    .action-pin, .action-edit, .action-delete {
      display: flex;
      align-items: center;
      margin-left: 20rpx;
      
      text {
        font-size: 24rpx;
        margin-left: 6rpx;
      }
    }
    
    .action-pin text {
      color: #FF9800;
    }
    
    .action-edit text {
      color: #32C5FF;
    }
    
    .action-delete text {
      color: #FF5252;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-image {
    width: 250rpx;
    height: 250rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 30rpx;
  }
  
  .create-btn {
    width: 300rpx;
    height: 80rpx;
    background: linear-gradient(135deg, #32C5FF, #BA68C8);
    color: #ffffff;
    border-radius: 40rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28rpx;
    
    &::after {
      border: none;
    }
  }
}

.loading-more, .no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  font-size: 24rpx;
  color: #999999;
  
  text {
    margin-left: 10rpx;
  }
}
</style> 